package top.ltc_cn.minecraft_manager.dto;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@Getter
@Setter
@Data
public class Oauth2JwksKeyResponse {

    private final List<Key> keys;

    @Getter
    @Setter
    @Data
    public static class Key {

        private final String kty;
        private final String use;
        private final String kid;
        private final String alg;
        private final String n; // modulus in Base64URL format
        private final String e; // exponent in Base64URL format

        public Key(String kty, String use, String kid, String alg, String n, String e) {
            this.kty = kty;
            this.use = use;
            this.kid = kid;
            this.alg = alg;
            this.n = n;
            this.e = e;
        }

        public Map<String, String> toMap() {
            return Map.of("kty", kty, "use", use, "kid", kid, "alg", alg, "n", n, "e", e);
        }

        public RSAPublicKey toRSAPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
            byte[] decodedModulus = Base64.getUrlDecoder().decode(n);
            byte[] decodedExponent = Base64.getUrlDecoder().decode(e);

            BigInteger modulus = new BigInteger(1, decodedModulus);
            BigInteger publicExponent = new BigInteger(1, decodedExponent);

            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        }
    }
}
